package com.corpgovernment.organization.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.corpgovernment.api.organization.bo.OrgAndDataPermissionInfoBO;
import com.corpgovernment.api.organization.bo.SearchInvoiceInfoRequestBO;
import com.corpgovernment.api.organization.bo.SearchInvoiceInfoResponseBO;
import com.corpgovernment.api.organization.bo.SearchOrgInfoRequestBO;
import com.corpgovernment.api.organization.model.enums.WholeGroupQueryEnum;
import com.corpgovernment.api.organization.model.ffpinfo.GetFfBasicsInfoResponse;
import com.corpgovernment.api.organization.model.org.GetOrgTreeResponse;
import com.corpgovernment.api.organization.model.org.ListOrgTreeByConditionResponse;
import com.corpgovernment.api.organization.model.org.OrgInfoVo;
import com.corpgovernment.api.organization.model.org.front.*;
import com.corpgovernment.api.organization.model.org.front.ListOrgTreeRequest.SortTypeEnum;
import com.corpgovernment.api.organization.model.org.queryorgparentcompany.QueryOrgParentCompanyRequest;
import com.corpgovernment.api.organization.model.org.queryorgparentcompany.QueryOrgParentCompanyResponse;
import com.corpgovernment.api.organization.model.org.request.*;
import com.corpgovernment.api.organization.model.org.response.*;
import com.corpgovernment.api.organization.model.settlement.QueryOrgInfoWithPermissionRequest;
import com.corpgovernment.api.organization.model.settlement.QueryOrgInfoWithPermissionResponse;
import com.corpgovernment.api.organization.vo.GetOrgTreeReq;
import com.corpgovernment.api.organization.vo.GetOrgTreeRsp;
import com.corpgovernment.api.organization.vo.TransferEmployeeOrgInfoVo;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.base.ResourceInfo;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.PayTypeEnum;
import com.corpgovernment.common.enums.ResourceEnum;
import com.corpgovernment.common.enums.SiteEnum;
import com.corpgovernment.common.handler.ICacheHandler;
import com.corpgovernment.common.operatelog.OperateLog;
import com.corpgovernment.common.operatelog.constant.OperateLogContant;
import com.corpgovernment.common.utils.BaseUtils;
import com.corpgovernment.common.utils.ObjectStringTrimUtils;
import com.corpgovernment.costcenter.service.impl.CostCenterServiceImpl;
import com.corpgovernment.organization.constant.CommonConst;
import com.corpgovernment.organization.constant.OrganizationConst;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.dto.AsyncDepartmentCompanyDTO;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.MbOrgPayType;
import com.corpgovernment.organization.enumm.CorpPayTypeEnum;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.event.OrgInitEvent;
import com.corpgovernment.organization.mapper.MbOrgInfoMapper;
import com.corpgovernment.organization.mapper.MbOrgInfoNewMapper;
import com.corpgovernment.organization.model.*;
import com.corpgovernment.organization.model.org.vo.CompanyRequest;
import com.corpgovernment.organization.service.*;
import com.corpgovernment.organization.util.OrganizationUtil;
import com.corpgovernment.organization.util.StrUtils;
import com.corpgovernment.organization.vo.FfpPageVo;
import com.corpgovernment.organization.vo.GetOrgTreeRequest;
import com.corpgovernment.permission.service.RoleResourceService;
import com.corpgovernment.permission.service.impl.MbRoleResourceServiceImpl;
import com.corpgovernment.redis.cache.RoleResourceManager;
import com.ctrip.corp.obt.generic.core.context.RequestContext;
import com.ctrip.corp.obt.generic.event.core.EventCenter;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.Collator;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.corpgovernment.api.organization.model.org.front.ListOrgTreeRequest.QuerySceneTypeEnum.*;
import static com.corpgovernment.permission.config.PermissionFilter.DATA_PERMISSION_ORG_ID_LIST;


/**
 * 组织控制器
 *
 * @author yujue.wang
 */
@RequestMapping(value = "/org")
@RestController
@Slf4j
@Api("组织操作")
public class OrganizationController {

    @Autowired
    private MbOrgInfoMapper mbOrgInfoMapper;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
    @Autowired
    private IOrgPayTypeService orgPayTypeService;
    @Autowired
    private IOrgUserIdCardService iOrgUserIdCardService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private com.corpgovernment.organization.service.IOrganizationEmployeeService organizationEmployeeService;
    @Autowired
    private ICacheHandler cacheHandler;
    @Autowired
    private RoleResourceService roleResourceService;
    @Autowired
    private MbOrgInfoNewMapper orgInfoNewMapper;
    @Autowired
    private RoleResourceManager manager;
    @Autowired
    private EventCenter eventCenter;
    @Autowired
    @Qualifier(value = "defaultThreadPoolExecutor")
    private ThreadPoolExecutor defaultThreadPoolExecutor;
    @Autowired
    private MbRoleResourceServiceImpl mbRoleResourceService;

    @Autowired
    private CostCenterServiceImpl costCenterService;
    @Autowired
    private OrganizationApollo organizationApollo;

    @Value("${login_time_out:7776000}")
    private long loginTimeOut;
    @Autowired
    private AsyncDepartmentCompanyService asyncDepartmentCompanyService;
    /**
     * 账号所属部门被禁用
     */
    public final static String ORG_DISABLE = "orgDisable";

    /**
     * 更新用户登录的有效性
     */
    private void updateTokenValid(List<String> orgIds, boolean flag) {
        for (String org : orgIds) {
            if (flag) {
                cacheHandler.setValue(ORG_DISABLE + ":" + org, true, loginTimeOut);//根据登录token的失效时间
            } else {
                cacheHandler.delete(ORG_DISABLE + ":" + org);
            }
        }
    }

    /**
     * 递归查找子节点
     *
     * @param treeNode    当前递归节点
     * @param parentIdMap 父级id组成的map
     * @return GetOrgTreeResponse
     */
    private static DepartmentallResponse findChildrenForFront(DepartmentallResponse
                                                                      treeNode, Map<String, List<MbOrgInfo>> parentIdMap) {
        List<MbOrgInfo> mbOrgInfos = parentIdMap.get(treeNode.getOrgId());
        if (CollectionUtils.isNotEmpty(mbOrgInfos)) {
            if (CollectionUtils.isEmpty(treeNode.getChildren())) {
                List<DepartmentallResponse> children = new ArrayList<>(mbOrgInfos.size());
                treeNode.setChildren(children);
            }
            List<DepartmentallResponse> children = treeNode.getChildren();
            for (MbOrgInfo mbOrgInfo : mbOrgInfos) {
                // 组装返回数据
                DepartmentallResponse getOrgTreeResponse = DepartmentallResponse.builder()
                        .id(mbOrgInfo.getId())
                        .label(mbOrgInfo.getName())
                        .parentId(mbOrgInfo.getParentId())
                        .disabled(!mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT))
                        .orgId(mbOrgInfo.getOrgId())
                        .build();
                // 如果当前层级为部门，也就是orgType为D的话，再将D对应orgId查询员工表，将员工表中间org_id等于当前部门id的人查询出来，插入进去
                children.add(findChildrenForFront(getOrgTreeResponse, parentIdMap));
            }
            treeNode.setChildren(children);
        }
        return treeNode;
    }

    /**
     * 递归查找子节点，只查询部门
     *
     * @param treeNode    当前递归节点
     * @param parentIdMap 父级id组成的map
     * @return GetOrgTreeResponse
     */
    private static DepartmentallResponse findChildrenWithoutCompanyForFront(DepartmentallResponse treeNode, Map<String, List<MbOrgInfo>> parentIdMap) {
        List<MbOrgInfo> mbOrgInfos = parentIdMap.get(treeNode.getOrgId());
        if (CollectionUtils.isNotEmpty(mbOrgInfos)) {
            if (CollectionUtils.isEmpty(treeNode.getChildren())) {
                List<DepartmentallResponse> children = new ArrayList<>(mbOrgInfos.size());
                treeNode.setChildren(children);
            }
            List<DepartmentallResponse> children = treeNode.getChildren();
            for (MbOrgInfo mbOrgInfo : mbOrgInfos) {
                if (mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT)) {
                    // 组装返回数据
                    DepartmentallResponse getOrgTreeResponse = DepartmentallResponse.builder()
                            .id(mbOrgInfo.getId())
                            .label(mbOrgInfo.getName())
                            .parentId(mbOrgInfo.getParentId())
                            .disabled(!mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT))
                            .orgId(mbOrgInfo.getOrgId())
                            .build();
                    // 如果当前层级为部门，也就是orgType为D的话，再将D对应orgId查询员工表，将员工表中间org_id等于当前部门id的人查询出来，插入进去
                    children.add(findChildrenWithoutCompanyForFront(getOrgTreeResponse, parentIdMap));
                }
            }
            treeNode.setChildren(children);
        }
        return treeNode;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNode    当前递归节点
     * @param parentIdMap 父级id组成的map
     * @return GetOrgTreeResponse
     */
    private static GetOrgTreeResponse findChildren(GetOrgTreeResponse treeNode,
                                                   Map<String, List<MbOrgInfo>> parentIdMap) {
        List<MbOrgInfo> mbOrgInfos = parentIdMap.get(treeNode.getOrgId());
        if (CollectionUtils.isNotEmpty(mbOrgInfos)) {
            if (CollectionUtils.isEmpty(treeNode.getChildren())) {
                List<GetOrgTreeResponse> children = new ArrayList<>(mbOrgInfos.size());
                treeNode.setChildren(children);
            }
            List<GetOrgTreeResponse> children = treeNode.getChildren();
            // 排序，公司在前，部门在后
            List<MbOrgInfo> companyList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()) && mbOrgInfo.getOrgType().equals(OrganizationConst.COMPANY))
                    .collect(Collectors.toList());
            List<MbOrgInfo> departmentList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()) && mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT))
                    .collect(Collectors.toList());
            List<MbOrgInfo> sortedList = new ArrayList<>(companyList.size() + departmentList.size());
            sortedList.addAll(companyList);
            sortedList.addAll(departmentList);
            for (MbOrgInfo mbOrgInfo : sortedList) {
                // 组装返回数据
                GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                        .id(mbOrgInfo.getOrgId())
                        .label(mbOrgInfo.getName())
                        .pid(mbOrgInfo.getParentId())
                        .level(mbOrgInfo.getLevel())
                        .type(mbOrgInfo.getOrgType())
                        .orgId(mbOrgInfo.getOrgId())
                        .valid(mbOrgInfo.getValid())
                        .build();
                // 如果当前层级为部门，也就是orgType为D的话，再将D对应orgId查询员工表，将员工表中间org_id等于当前部门id的人查询出来，插入进去
                children.add(findChildren(getOrgTreeResponse, parentIdMap));
            }
            treeNode.setChildren(children);
        }
        return treeNode;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNode    当前递归节点
     * @param parentIdMap 父级id组成的map
     * @return GetOrgTreeResponse
     */
    private static GetOrgTreeResponse findChildrenWithoutCompany(GetOrgTreeResponse treeNode,
                                                                 Map<String, List<MbOrgInfo>> parentIdMap) {
        List<MbOrgInfo> mbOrgInfos = parentIdMap.get(treeNode.getOrgId());
        if (CollectionUtils.isNotEmpty(mbOrgInfos)) {
            if (CollectionUtils.isEmpty(treeNode.getChildren())) {
                List<GetOrgTreeResponse> children = new ArrayList<>(mbOrgInfos.size());
                treeNode.setChildren(children);
            }
            List<GetOrgTreeResponse> children = treeNode.getChildren();
            // 排序，公司在前，部门在后
            List<MbOrgInfo> departmentList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()) && mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT))
                    .collect(Collectors.toList());
            List<MbOrgInfo> sortedList = new ArrayList<>(departmentList.size());
            sortedList.addAll(departmentList);
            for (MbOrgInfo mbOrgInfo : sortedList) {
                // 组装返回数据
                GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                        .id(mbOrgInfo.getOrgId())
                        .label(mbOrgInfo.getName())
                        .pid(mbOrgInfo.getParentId())
                        .level(mbOrgInfo.getLevel())
                        .type(mbOrgInfo.getOrgType())
                        .orgId(mbOrgInfo.getOrgId())
                        .valid(mbOrgInfo.getValid())
                        .build();
                // 如果当前层级为部门，也就是orgType为D的话，再将D对应orgId查询员工表，将员工表中间org_id等于当前部门id的人查询出来，插入进去
                children.add(findChildrenWithoutCompany(getOrgTreeResponse, parentIdMap));
            }
            treeNode.setChildren(children);
        }
        return treeNode;
    }

    public static List<GetOrgTreeResponse> removeCompanyAndFuzzyName(GetOrgTreeResponse getOrgTreeResponse, String name) {
        List<GetOrgTreeResponse> tempList = new ArrayList<>();
        List<GetOrgTreeResponse> children = Optional.ofNullable(getOrgTreeResponse.getChildren()).orElse(new ArrayList<>());

        for (GetOrgTreeResponse child : children) {
            if (StringUtils.isBlank(name)) {
                if (child.getType().equals(OrganizationConst.DEPARTMENT)) {
                    List<GetOrgTreeResponse> childList = removeCompanyAndFuzzyName(child, name);
                    child.setChildren(childList);
                    tempList.add(child);
                }
            } else {
                if (child.getType().equals(OrganizationConst.DEPARTMENT) && child.getLabel().contains(name)) {
                    List<GetOrgTreeResponse> childList = removeCompanyAndFuzzyName(child, name);
                    child.setChildren(childList);
                    tempList.add(child);
                } else if (child.getType().equals(OrganizationConst.DEPARTMENT) && !child.getLabel().contains(name)) {
                    tempList.addAll(removeCompanyAndFuzzyName(child, name));
                }
            }

        }
        return tempList;
    }

    /**
     * 更新组织信息
     *
     * @param request
     * @return
     */
    @PostMapping("/updateOrgInfo")
    @OperateLog(OperateLogContant.UPDATEORGINFO)
    public JSONResult<Long> updateOrgInfo(@RequestBody @Valid UpdateOrgRequest request) {
        return organizationInfoService.updateOrgInfo(request);
    }

    /**
     * 获取组织架构信息
     *
     * @param request req
     * @return GetOrgInfoResponse
     */
    @PostMapping("/get")
    public JSONResult<GetOrgInfoResponseNew> getOrgInfo(@RequestBody @Valid GetOrgInfoRequest request) {
        return organizationInfoService.getOrgInfo(request);
    }

    /**
     * 删除组织架构信息
     *
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public JSONResult<DeleteResponse> delete(@RequestBody @Valid DeleteRequest request, BaseUserInfo baseUserInfo) {
        return new JSONResult<>(organizationInfoService.delete(request, baseUserInfo));
    }


    /****************************以上是标准版新写的接口*********************/

    /**
     * 更新组织基本信息
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/updateBaseOrgInfo")
    JSONResult<Boolean> updateBaseOrgInfo(@RequestBody @Valid UpdateBaseOrgInfoRequest request) {
        MbOrgInfo orgInfo = organizationInfoService.findByBusinessCode(request.getNewBusinessCode());
        String orgTypeDesc = OrgTypeEnum.getByCode(request.getType()).getDesc();
        if (StrUtils.havingChinese(request.getNewBusinessCode())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.NEW_BUSINESS_CODE_FORMAT_ERROR);
        }
        if (StringUtils.isNotBlank(request.getNewBusinessCode()) && request.getNewBusinessCode().length() > 100) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.NEW_BUSINESS_CODE_LENGTH_OUT, orgTypeDesc);
        }
        if (StringUtils.isNotBlank(request.getName()) && request.getName().length() > 20) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_NAME_LENGTH_OUT);
        }
        if (orgInfo != null && !orgInfo.getOrgId().equalsIgnoreCase(request.getOrgId())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.NEW_BUSINESS_CODE_EXISTS, orgTypeDesc, orgTypeDesc);
        }
        if (StringUtils.isBlank(request.getNewBusinessCode())) {
            request.setBusinessCode(request.getOrgId());
        }
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setOrgId(request.getOrgId());
        mbOrgInfo.setName(request.getName());
        mbOrgInfo.setBusinessCode(request.getNewBusinessCode());
        organizationInfoService.updateParentBusinessCode(request.getBusinessCode(), request.getNewBusinessCode());
        boolean flag = organizationInfoService.updateBaseOrgInfo(mbOrgInfo);

        // 修改成本中心
        if(request.getEditCostCenterFlag()) {
            // 删除该组织和默认成本中心的关系
            costCenterService.deleteCostDepartmentByOrgId(request.getOrgId(), 2);
            // 删除该组织和成本中心的关系
            costCenterService.deleteCostDepartmentByOrgId(request.getOrgId(), 1);

            // 保存成本中心
            costCenterService.saveCostCenterInfoByOrg(request.getOrgId(),
                    request.getCostCenterInfoList().stream().map(data -> {
                        AddOrgRequest.CostCenterInfo costCenterInfo = new AddOrgRequest.CostCenterInfo();
                        costCenterInfo.setCostCenterCode(data.getCostCenterCode());
                        costCenterInfo.setCostCenterName(data.getCostCenterName());
                        return costCenterInfo;
                    }).collect(Collectors.toList()));
            //保存默认成本中心
            AddOrgRequest.CostCenterInfo costCenterInfoDefault = new AddOrgRequest.CostCenterInfo();
            costCenterInfoDefault.setCostCenterCode(request.getCostCenterInfoDefault().getCostCenterCode());
            costCenterInfoDefault.setCostCenterName(request.getCostCenterInfoDefault().getCostCenterName());
            costCenterService.saveOrgCostDefaultDepartmentByOrg(request.getOrgId(), costCenterInfoDefault);
        }
        return new JSONResult<>(flag);
    }

    /**
     * 查询所有公司*
     *
     * @return 子公司列表集合
     */
    @RequestMapping("/findAllCompanyInfoGroupByLevel")
    public JSONResult<Map> findAllCompanyInfoGroupByLevel(BaseUserInfo baseUserInfo) {
        return organizationInfoService.findAllCompanyInfoGroupByLevel(baseUserInfo);
    }

    @RequestMapping("/searchComapny")
    public JSONResult<RoutCompanyVo> searchComapny(String keyword) {
        return organizationInfoService.searchComapny(keyword);
    }

    /**
     * 组织架构/岗位—添加部门/子公司
     *
     * @param addOrgRequest
     * @return
     */
    @RequestMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public JSONResult<String> add(@RequestBody @Valid AddOrgRequest addOrgRequest, BaseUserInfo baseUserInfo) {
        log.info("add addOrgRequest before:{}", addOrgRequest);
        ObjectStringTrimUtils.allFieldRemoveWarp(addOrgRequest);
        log.info("add addOrgRequest:{}", addOrgRequest);

        String orgId = addOrgRequest.getOrgId();
        String name = addOrgRequest.getName();
        String type = addOrgRequest.getType();
        String newBusinessCode = addOrgRequest.getNewBusinessCode();
        String businessCode = addOrgRequest.getBusinessCode();
        String orgTypeDesc = OrgTypeEnum.getByCode(addOrgRequest.getType()).getDesc();
        checkParams(addOrgRequest, orgTypeDesc);
        // 查询父级组织结构信息
        int level = 1;
        if (StrUtil.isNotEmpty(orgId)) {
            MbOrgInfo parentOrgInfo = organizationInfoService.findByOrgId(orgId);
            if (parentOrgInfo == null) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.PARENT_ORG_IS_NULL);
            }
            level = parentOrgInfo.getLevel() + 1;
        }
        String newOrgId = organizationInfoService.createOrgCode(orgId);
        MbOrgInfo orgInfo = organizationInfoService.findByOrgId(newOrgId);
        if (orgInfo != null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_INFO_IS_NULL);
        }
        if (StringUtils.isBlank(newBusinessCode)) {
            newBusinessCode = newOrgId;
        }
        orgInfo = organizationInfoService.findByBusinessCode(newBusinessCode);
        if (orgInfo != null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.NEW_BUSINESS_CODE_EXISTS, orgTypeDesc, orgTypeDesc);
        }
        // 插入org表
        Long id = saveOrgInfo(orgId, name, type, level, newOrgId, newBusinessCode, businessCode);
        if (id == null) {
            log.info("保存组织架构数据入DB失败");
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SAVE_ORG_FAILED);
        }
        //非后台用户创建部门直接添加至角色下
        if (!baseUserInfo.getBgUser()) {
            mbRoleResourceService.addOneResource(baseUserInfo.getRoleId(), id, newOrgId, type, ResourceEnum.DEPT.getCode());
        }

        //初始化组织设置
        OrgInitEvent orgInitEvent = new OrgInitEvent();
        OrgInitEvent.InitOrgPayType initOrgPayType = new OrgInitEvent.InitOrgPayType();
        initOrgPayType.setOrgId(newOrgId);
        initOrgPayType.setOrgType(type);
        orgInitEvent.setInitOrgPayType(initOrgPayType);
        eventCenter.post(orgInitEvent);

        //保存成本中心
        if (CollectionUtils.isNotEmpty(addOrgRequest.getCostCenterInfoList())) {
            //保存成本中心
            costCenterService.saveCostCenterInfoByOrg(newOrgId, addOrgRequest.getCostCenterInfoList());
        }
        if(addOrgRequest.getCostCenterInfoDefault() != null) {
            //保存默认成本中心
            costCenterService.saveOrgCostDefaultDepartmentByOrg(newOrgId, addOrgRequest.getCostCenterInfoDefault());
        }
        // 异步处理新增部门权限后需要处理的开票、代订、成本中心、项目...
        // Apollo开关异步处理新增部门或者公司,true:异步处理 ; false:不处理
        try {
            // 异步处理新增部门或公司
            asyncDepartmentCompany(orgId, newOrgId, name, type, id);
        } catch (Exception e) {
            log.error("addOrgRequest:{},baseUserInfo:{}",JsonUtils.toJsonString(addOrgRequest),JsonUtils.toJsonString(baseUserInfo));
            log.error("Apollo开关异步处理新增部门或者公司开关异常",e);
        }
        return JSONResult.success(newOrgId);
    }

    /**
     * 异步处理新增部门或公司
     *
     * @param orgId 父级组织ID
     * @param newOrgId 新增的组织ID
     * @param name 新增的组织名称
     * @param type 组织类型
     * @param id 新增的组织ID
     */
    private void asyncDepartmentCompany(String orgId, String newOrgId, String name, String type, Long id) {
        String asyncAddDepartmentOrCompany = organizationApollo.getAsyncAddDepartmentOrCompany();
        log.info("Apollo开关异步处理新增部门或者公司开关,asyncAddDepartmentOrCompany:{}",asyncAddDepartmentOrCompany);
        if("true".equalsIgnoreCase(asyncAddDepartmentOrCompany)){
            AsyncDepartmentCompanyDTO asyncDepartmentCompanyDTO = AsyncDepartmentCompanyDTO.builder()
                    .parentOrgId(orgId)
                    .newOrgId(newOrgId)
                    .newOrgName(name)
                    .type(type)
                    .newId(String.valueOf(id)).build();
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                asyncDepartmentCompanyService.handle(asyncDepartmentCompanyDTO);
                return "";
            },defaultThreadPoolExecutor);

            try {
                future.get();
            } catch (Exception e) {
                log.error("异步处理新增部门或公司异常:",e);
            }
        }
    }

    private void checkParams(AddOrgRequest addOrgRequest, String orgTypeDesc) {
        if (StringUtils.isBlank(orgTypeDesc)){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_TYPE_IS_NULL);
        }
        if (StringUtils.isBlank(addOrgRequest.getType())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.NEW_BUSINESS_CODE_FORMAT_ERROR);
        }
        if (StringUtils.isBlank(addOrgRequest.getNewBusinessCode())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.COMPANY_IS_NULL, orgTypeDesc);
        }
        if (StrUtils.havingChinese(addOrgRequest.getNewBusinessCode())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.NEW_BUSINESS_CODE_FORMAT_ERROR);
        }
        if (addOrgRequest.getName() != null && addOrgRequest.getName().length() > 100) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.NEW_BUSINESS_CODE_LENGTH_OUT, orgTypeDesc);
        }
        if (addOrgRequest.getNewBusinessCode().length() > 100) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.NEW_BUSINESS_CODE_LENGTH_OUT, orgTypeDesc);
        }

    }

    /**
     * 组织架构/岗位—启用/禁用
     * <p>
     * 1，组织类型为公司时，选择禁用-禁用当前公司及各部门，不往下穿透子公司，启用时一同启用；
     * <p>
     * 2，组织类型为部门时，选择禁用-禁用当前部门及子部门，不穿透子公司，启用时一同启用；
     * <p>
     * 3，上级组织为禁用时，当前组织不可启用
     * <p>
     * 4，组织的禁用启用跟人员不联动
     *
     * @param validOrgRequest
     * @return
     */
    @RequestMapping("/validOrg")
    public JSONResult<Boolean> validOrg(@RequestBody @Valid ValidOrgRequest validOrgRequest) {
        // 操作类型：0禁用   1启用
        String enableStatus = validOrgRequest.getEnableStatus();
        String orgId = validOrgRequest.getOrgId();

        // 如果enableStatus是启用，还需要查询当前org的上级组织结构是否是有禁用状态，如果有，则提示不能启用
        if ("1".equals(enableStatus)) {
            MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);
            String parentId = mbOrgInfo.getParentId();
            if (StrUtil.isNotBlank(parentId)) {
                MbOrgInfo parentOrgInfo = organizationInfoService.findByOrgId(parentId);
                if (parentOrgInfo.getValid().equals(CommonConst.FALSE)) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.PARENT_ORG_VALID);
                }
            }
        }
        // 查询所有下级部门ids
        List<String> orgIds = organizationInfoService.listAllDepartmentByOrgId(orgId);
        // 修改组织状态
        boolean flag = organizationInfoService.batchUpdateStatus(orgIds, "0".equals(enableStatus) ? CommonConst.FALSE : CommonConst.TRUE);

        log.info("更新的部门ids", orgIds);
        // 记录到redis中,网关中判断是否禁用
        //0为禁用
        updateTokenValid(orgIds, "0".equals(enableStatus));
        return new JSONResult<>(flag);
    }

    /**
     * 查询组织下所有子部门（不包含该组织），不穿透子公司
     */
    @RequestMapping("/listAllDepartments")
    public JSONResult<List<OrgInfoVo>> listAllDepartments(@RequestParam(name = "orgId") String orgId, @RequestParam(name = "withDeleted") Boolean withDeleted) {
        List<MbOrgInfo> mbOrgInfos = organizationInfoService.listAllDepartments(orgId, withDeleted);
        if (!BaseUtils.isNotNull(mbOrgInfos)) {
            return JSONResult.success(Lists.newArrayList());
        }
        List<OrgInfoVo> result = mbOrgInfos.stream().filter(o -> o != null).map(o -> JsonUtils.convert(o, OrgInfoVo.class)).collect(Collectors.toList());
        return JSONResult.success(result);
    }

    /**
     * 查询组织下直属子部门（包含该组织），不穿透子公司
     */
    @RequestMapping("/listAllDepartmentsByParentId")
    public JSONResult<List<OrgInfoVo>> listAllDepartmentsByParentId(@RequestParam(name = "parentId") String parentId, @RequestParam(name = "withDeleted") Boolean withDeleted) {
        List<OrgInfoVo> result = Lists.newArrayList();
        MbOrgInfo orgInfo = organizationInfoService.findByOrgId(parentId, withDeleted);
        if (orgInfo != null) {
            result.add(JsonUtils.convert(orgInfo, OrgInfoVo.class));
        }
        List<MbOrgInfo> mbOrgInfos = organizationInfoService.listAllDepartmentsByParentId(parentId, withDeleted);
        if (!BaseUtils.isNotNull(mbOrgInfos)) {
            return JSONResult.success(result);
        }
        result.addAll(mbOrgInfos.stream().filter(o -> o != null).map(o -> JsonUtils.convert(o, OrgInfoVo.class)).collect(Collectors.toList()));
        return JSONResult.success(result);
    }

    /**
     * 查询组织下所有子部门id（不包含该组织），不穿透子公司
     */
    @RequestMapping("/listAllDepartmentIds")
    public JSONResult<List<String>> listAllDepartmentIds(@RequestParam(name = "orgId") String orgId, @RequestParam(name = "withDeleted") Boolean withDeleted) {
        return JSONResult.success(organizationInfoService.listAllDepartmentIds(orgId, withDeleted));
    }

    /**
     * 根据用户查询树
     *
     * @return
     */
    @RequestMapping("/departmentall")
    @ResponseBody
    public JSONResult<List<DepartmentallResponse>> departmentall(HttpServletRequest request) {
        String uid = request.getParameter("uId");
        String userName = request.getParameter("userName");
        // 根据uid查询权限
        if (StringUtils.isBlank(uid)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.UID_NULL);
        }
        MbOrgEmployeeInfo userInfo = organizationEmployeeService.findAllByUid(uid);
        if (userInfo == null || StringUtils.isBlank(userInfo.getUid())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_ALREADY_EXISTS);
        }
        List<DepartmentallResponse> returnList = new ArrayList<>();
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAll();
        // parentId 下 组织结构列表 map
        Map<String, List<MbOrgInfo>> parentListMap = mbOrgInfoList.stream()
                .filter(p -> p.getParentId() != null)
                .collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        // orgid 对应实体 map
        Map<String, MbOrgInfo> orgInfoMap = mbOrgInfoList.stream()
                .filter(p -> StringUtils.isNotBlank(p.getOrgId()))
                .collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        // 小权限
        if (!userInfo.getIsBackground()) {
            // 查询到用户的根公司
            MbOrgInfo mbOrgInfo = organizationInfoService.findRecentCompanyIdByOrgId(userInfo.getOrgId());
            if (mbOrgInfo == null) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_INFO_IS_NULL);
            }
            DepartmentallResponse departmentallResponse = new DepartmentallResponse();
            departmentallResponse.setOrgId(mbOrgInfo.getOrgId());
            departmentallResponse.setLabel(mbOrgInfo.getName());
            departmentallResponse.setId(mbOrgInfo.getId());
            departmentallResponse.setParentId(mbOrgInfo.getParentId());
            departmentallResponse.setDisabled(true);
            findChildrenWithoutCompanyForFront(departmentallResponse, parentListMap);
            returnList.add(departmentallResponse);
            return new JSONResult(returnList);
        }
        // 大权限
        // 一级level数据
        List<String> firstLevelOrgIds = mbOrgInfoList.stream()
                .filter(p -> p.getLevel() != null && p.getLevel() == 1)
                .map(MbOrgInfo::getOrgId)
                .distinct()
                .collect(Collectors.toList());
        for (String firstLevelOrgId : firstLevelOrgIds) {
            DepartmentallResponse departmentallResponse = new DepartmentallResponse();
            MbOrgInfo mbOrgInfo = orgInfoMap.get(firstLevelOrgId);
            departmentallResponse.setOrgId(firstLevelOrgId);
            departmentallResponse.setLabel(mbOrgInfo.getName());
            departmentallResponse.setId(mbOrgInfo.getId());
            departmentallResponse.setParentId(mbOrgInfo.getParentId());
            departmentallResponse.setDisabled(true);
            departmentallResponse = findChildrenForFront(departmentallResponse, parentListMap);
            returnList.add(departmentallResponse);
        }
        return new JSONResult<>(returnList);
    }

    /**
     * 查询组织下所有子部门id（包含该组织），不穿透子公司
     */
    @RequestMapping("/listAllGroupDepartmentIds")
    public JSONResult<Map<String, List<String>>> listAllGroupDepartmentIds(@RequestParam(name = "orgIds") List<String> orgIds, @RequestParam(name = "withDeleted") Boolean withDeleted) {
        Map<String, List<String>> result = Maps.newHashMap();
        if (!BaseUtils.isNotNull(orgIds)) {
            log.info("orgIds为空");
            return JSONResult.success(result);
        }
        orgIds.forEach(orgId -> {
            List<String> data = organizationInfoService.listAllDepartmentIds(orgId, withDeleted);
            if (data == null) {
                data = Lists.newArrayList();
            }
            data.add(orgId);
            result.put(orgId, data);
        });
        return JSONResult.success(result);
    }


    /**
     * 查询组织下（不包含该组织）所有子公司id
     */
    @RequestMapping("/listAllCorpIds")
    public JSONResult<List<String>> listAllCorpIds(@RequestParam(name = "orgId") String orgId, @RequestParam(name = "withDeleted") Boolean withDeleted) {
        return JSONResult.success(organizationInfoService.listAllCorpIds(orgId, withDeleted));
    }

    /**
     * 修改酒店支付方式
     *
     * @param updateHotelPayTypeRequest
     * @return
     */
    @RequestMapping("/updateHotelPayType")
    public JSONResult<UpdateHotelPayTypeResponse> updateHotelPayType(@RequestBody UpdateHotelPayTypeRequest updateHotelPayTypeRequest) {
        String type = updateHotelPayTypeRequest.getType();
        Boolean enable = updateHotelPayTypeRequest.getEnable();
        String orgId = updateHotelPayTypeRequest.getOrgId();
        // 点击停用个付的时候，需要判断另一种支付是否是启用的（注意统付需要保证所有的部门都选中），
        // 若有部门当前只有一种支付方式，点击停用，出提示信息“当前有部门仅支持此支付方式，不可取消！”需要保证当前公司，包含部门至少要支持一种支付方式。
        if (!enable && StrUtil.equals(PayTypeEnum.PPAY.getType(), type)) {
            return cancelHotelPpay(orgId);
        }
        // 启用酒店个人支付
        if (enable && StrUtil.equals(PayTypeEnum.PPAY.getType(), type)) {
            return enableHotelPpay(orgId);
        }
        return new JSONResult<>(new UpdateHotelPayTypeResponse());
    }

    /**
     * 修改公司的酒店统一支付范围
     *
     * @param updateHotelAccntPayTypeRequest
     * @return
     */
    @RequestMapping("/updateHotelAccntPayType")
    public JSONResult<Boolean> updateHotelAccntPayType(@RequestBody UpdateHotelAccntPayTypeRequest updateHotelAccntPayTypeRequest) {
        String orgId = updateHotelAccntPayTypeRequest.getOrgId();
        List<String> departmentList = organizationInfoService.listAllDepartmentByOrgId(orgId);
        String supplierId = updateHotelAccntPayTypeRequest.getSupplierId();
        // 移除组织下的所有部门支付方式
        orgPayTypeService.delete(departmentList, PayTypeEnum.ACCNT.getType(), SiteEnum.HOTEL.getCode(), supplierId, true);
        List<String> orgIds = updateHotelAccntPayTypeRequest.getOrgIdArr();
        // 批量保存
        if (CollectionUtils.isNotEmpty(orgIds)) {
            CollUtil.distinct(orgIds);
            for (String id : orgIds) {
                MbOrgPayType mbOrgPayType = new MbOrgPayType();
                mbOrgPayType.setOrgId(id);
                mbOrgPayType.setSite(SiteEnum.HOTEL.getCode());
                mbOrgPayType.setPaytype(PayTypeEnum.ACCNT.getType());
                mbOrgPayType.setSuppliercode(supplierId);
                orgPayTypeService.save(mbOrgPayType);
            }
        }
        return new JSONResult<>(true);
    }

    /**
     * 启用酒店个人支付
     *
     * @param orgId
     * @return
     */
    private JSONResult<UpdateHotelPayTypeResponse> enableHotelPpay(String orgId) {
        List<String> orgIds = organizationInfoService.listAllDepartmentByOrgId(orgId);
        CollUtil.distinct(orgIds);
        for (String id : orgIds) {
            MbOrgPayType mbOrgPayType = new MbOrgPayType();
            mbOrgPayType.setOrgId(id);
            mbOrgPayType.setSite(SiteEnum.HOTEL.getCode());
            mbOrgPayType.setPaytype(PayTypeEnum.PPAY.getType());
            orgPayTypeService.save(mbOrgPayType);
        }
        return returnUpdateHotelPayType(200);
    }

    /**
     * 取消酒店个人支付
     *
     * @param orgId
     * @return
     */
    private JSONResult<UpdateHotelPayTypeResponse> cancelHotelPpay(String orgId) {
        List<String> departmentList = organizationInfoService.listAllDepartmentByOrgId(orgId);
        // 如果子公司下部门为空
        if (CollUtil.isEmpty(departmentList)) {
            // 只需要判断当前公司是否有统一支付
            List<MbOrgPayType> mbOrgPayTypeList = orgPayTypeService.listByOrgIds(CollUtil.newArrayList(orgId), SiteEnum.HOTEL.getCode(), null, null);
            List<MbOrgPayType> accntPayList = mbOrgPayTypeList.stream().filter(p -> StrUtil.equals(p.getPaytype(), PayTypeEnum.ACCNT.getType())).collect(Collectors.toList());
            if (CollUtil.isEmpty(accntPayList)) {
                return returnUpdateHotelPayType(-1);
            }
            orgPayTypeService.setPPayByOrgIds(CollUtil.newArrayList(orgId), PayTypeEnum.PPAY.getType(), SiteEnum.HOTEL.getCode(), null);
            return returnUpdateHotelPayType(200);
        }
        List<MbOrgPayType> orgPayTypeList = orgPayTypeService.listByOrgIds(departmentList, SiteEnum.HOTEL.getCode(), null, null);
        List<MbOrgPayType> accntList = orgPayTypeList.stream().filter(p -> StrUtil.equals(p.getPaytype(), PayTypeEnum.ACCNT.getType())).collect(Collectors.toList());
        if (CollUtil.isEmpty(accntList) || departmentList.size() > accntList.size()) {
            return returnUpdateHotelPayType(-1);
        }
        orgPayTypeService.delete(departmentList, PayTypeEnum.PPAY.getType(), SiteEnum.HOTEL.getCode(), null, Boolean.TRUE);
        return returnUpdateHotelPayType(200);
    }

    /**
     * 封装修改酒店支付返回值
     *
     * @param code 状态码 成功200 失败-1
     * @return
     */
    private JSONResult<UpdateHotelPayTypeResponse> returnUpdateHotelPayType(Integer code) {
        UpdateHotelPayTypeResponse updateHotelPayTypeResponse = new UpdateHotelPayTypeResponse();
        updateHotelPayTypeResponse.setCode(code);
        return new JSONResult<>(updateHotelPayTypeResponse);
    }

    /**
     * 查询组织架构下所有部门子组织结构，包含当前orgId
     *
     * @param orgId 组织结构id
     * @return
     */
    @RequestMapping(value = "/findChildrenDepOrgListByOrgId")
    public JSONResult<List<String>> findChildrenDepOrgListByOrgId(@RequestParam("orgId") String orgId) {
        return JSONResult.success(organizationInfoService.listRecentCompanyAllDepartmentByOrgId(orgId));
    }

    /**
     * 保存组织架构信息
     *
     * @param orgId    父级组织id
     * @param name     组织名称
     * @param type     组织类型
     * @param level    组织level层级
     * @param newOrgId 当前新增的组织结构id
     * @return
     */
    private Long saveOrgInfo(String orgId, String name, String type, int level, String newOrgId, String newBusinessCode, String businessCode) {
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setName(name);
        mbOrgInfo.setOrgType(type);
        mbOrgInfo.setParentId(orgId);
        mbOrgInfo.setOrgId(newOrgId);
        mbOrgInfo.setLevel(level);
        mbOrgInfo.setBusinessCode(newBusinessCode);
        mbOrgInfo.setParentBusinessCode(businessCode);
        // 新建的组织，默认启用
        mbOrgInfo.setValid(CommonConst.TRUE);
        boolean flag = organizationInfoService.createOrgInfo(mbOrgInfo);
        if (flag){
            return mbOrgInfo.getId();
        }
        return null;
    }

    private void savePayType(String orgId, String site, String paytype, String supplierCode) {
        MbOrgPayType mbOrgPayType = new MbOrgPayType();
        mbOrgPayType.setCorpPayType(CorpPayTypeEnum.OWN.toString());
        mbOrgPayType.setOrgId(orgId);
        mbOrgPayType.setPaytype(paytype);
        mbOrgPayType.setSite(site);
        mbOrgPayType.setSuppliercode(supplierCode);
        orgPayTypeService.save(mbOrgPayType);
    }

    /**
     * 组织架构/岗位—编辑绑定财务公司
     *
     * @param bindFinanceRequest
     * @return
     */
    @RequestMapping("/bind")
    public JSONResult<Boolean> bind(@RequestBody @Valid BindFinanceRequest bindFinanceRequest) {
        String orgId = bindFinanceRequest.getOrgId();
        String bindOrgName = bindFinanceRequest.getBindOrgName();
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setOrgId(orgId);
        mbOrgInfo.setBindName(bindOrgName);
        boolean flag = organizationInfoService.update(mbOrgInfo);
        return new JSONResult<>(flag);
    }

    /**
     * 查询公司下所有部门
     *
     * @param listCompanyAllDepartmentRequest request
     * @return
     */
    @RequestMapping("/listCompanyAllDepartment")
    public JSONResult<OrgTreeNode> listCompanyAllDepartment(@RequestBody @Valid ListCompanyAllDepartmentRequest listCompanyAllDepartmentRequest) {
        return new JSONResult<>(null);
    }

    /**
     * 查询组织所属公司
     */
    @PostMapping("/queryOrgParentCompany")
    public JSONResult<QueryOrgParentCompanyResponse> queryOrgParentCompany(
        @RequestBody QueryOrgParentCompanyRequest request) {
        return JSONResult.success(organizationInfoService.queryOrgParentCompany(request));
    }

    /**
     * 查询用户id查询用户所在直属子公司信息
     *
     * @param uid   用户id
     * @param orgId 组织结构id
     * @return 子公司信息
     */
    @RequestMapping(value = "/findRecentCompanyInfoByUid")
    public JSONResult<OrgInfoVo> findRecentCompanyInfoByUid(@RequestParam(value = "uid") String uid, @RequestParam(value = "orgId") String orgId) {
        MbOrgInfo mbOrgInfo = organizationInfoService.findRecentCompanyIdByOrgId(orgId);
        OrgInfoVo orgInfoVo = new OrgInfoVo();
        if (mbOrgInfo != null) {
            BeanUtils.copyProperties(mbOrgInfo, orgInfoVo);
        }
        return new JSONResult<>(orgInfoVo);
    }

    /**
     * 查询用户id查询用户所在直属子公司信息 New
     *
     * @return 子公司信息
     */
    @RequestMapping(value = "/findRecentCompanyInfoByUidNew")
    public JSONResult<OrgInfoVo> findRecentCompanyInfoByUidNew(@RequestBody OrgInfoVo request) {
        MbOrgInfo mbOrgInfo = organizationInfoService.findRecentCompanyIdByOrgId(request.getOrgId());
        OrgInfoVo orgInfoVo = new OrgInfoVo();
        if (mbOrgInfo != null) {
            BeanUtils.copyProperties(mbOrgInfo, orgInfoVo);
        }
        return new JSONResult<>(orgInfoVo);
    }

    /**
     * 获取一个组织信息
     * 后端接口
     * http://localhost:7890/org/findOrgInfoByOrgId
     *
     * @param orgId 组织架构id
     * @return JSONResult
     */
    @RequestMapping("/findOrgInfoByOrgId")
    @ResponseBody
    public JSONResult<OrgInfoVo> findOrgInfoByOrgId(@RequestParam(name = "orgId") String orgId) {
        return JSONResult.success(organizationInfoService.searchOrgInfo(SearchOrgInfoRequestBO.create(orgId)));
    }

    @RequestMapping("/findOrgInfoByOrgIds")
    @ResponseBody
    public JSONResult<List<OrgInfoVo>> findOrgInfoByOrgIds(@RequestParam(name = "orgIds") List<String> orgIds) {
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listByOrgIds(orgIds);
        // 查找组织结构信息
        if (CollectionUtils.isEmpty(mbOrgInfoList)) {
            return JSONResult.errorMsg("没有找到组织结构数据");
        }
        List<OrgInfoVo> orgInfoList = mbOrgInfoList.stream().map(e -> {
            OrgInfoVo orgInfoVo = new OrgInfoVo();
            BeanUtils.copyProperties(e, orgInfoVo);
            return orgInfoVo;
        }).collect(Collectors.toList());
        return new JSONResult<>(orgInfoList);
    }

    /**
     * 根据组织编码查询组织信息
     * 先查询未删除的 -> 没查到则返回删除的
     *
     * @param orgIds
     * @return
     */
    @RequestMapping("/findOrgInfoOrHistoryByOrgIds")
    @ResponseBody
    public JSONResult<List<OrgInfoVo>> findOrgInfoOrHistoryByOrgIds(@RequestParam(name = "orgIds") List<String> orgIds) {
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAllByOrgIds(orgIds);
        if (CollectionUtils.isEmpty(mbOrgInfoList)) {
            return new JSONResult<>(Collections.emptyList());
        }
        Map<String, List<MbOrgInfo>> orgMap =
            mbOrgInfoList.stream().collect(Collectors.groupingBy(item -> item.getOrgId()));
        List<OrgInfoVo> result = new ArrayList<>(orgIds.size());
        orgMap.forEach((orgId, orgInfoList) -> {
            Optional<MbOrgInfo> firstOrgInfo =
                orgInfoList.stream().filter(item -> item.getDeleteTime().compareTo(new Date(0)) <= 0).findFirst();
            OrgInfoVo orgInfoVo = new OrgInfoVo();
            if (firstOrgInfo.isPresent()) {
                BeanUtils.copyProperties(firstOrgInfo.get(), orgInfoVo);
                result.add(orgInfoVo);
            } else {
                BeanUtils.copyProperties(orgInfoList.get(0), orgInfoVo);
                result.add(orgInfoVo);
            }
        });
        return new JSONResult<>(result);
    }

    /**
     * 根据用户id查询部门树
     * 前端接口
     * 契约文档地址：http://10.5.119.87:9526/project/11/interface/api/131
     * 访问url：http://localhost:7890/org/listOrgTreeByUserId
     *
     * @return
     */
    @PostMapping("/listOrgTreeByUserId")
    @ResponseBody
    @ApiOperation("组织树查询")
    public JSONResult<List<GetOrgTreeResponse>> listOrgTreeByUserId(@RequestBody ListOrgTreeRequest reuqest, BaseUserInfo baseUserInfo) {
        // 查询用户信息，判断是否是后台员工
        Boolean bgUser = baseUserInfo.getBgUser();
        String goalOrgId = reuqest.getId();
        Boolean ifShowChildCompany = reuqest.getIfShowChildCompany();
        Boolean ifStartWithCompany = reuqest.getIfStartWithCompany();
        String sortType = reuqest.getSortType();
        // 查询所有组织结构
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAll();
        // 代订展示所有组织树
        if ((BOOKING_RELATION_ADD_RANGE.toString().equals(reuqest.getQueryScene())
            || BOOKING_RELATION_ADD_USER.toString().equals(reuqest.getQueryScene()))
            && organizationApollo.enableBookingRelationShowAllOrg()) {
            return new JSONResult<>(listOrgTreeAndSort(mbOrgInfoList, null, true, sortType));
        }
        // 审批展示所有组织树
        if(APPROVE.toString().equalsIgnoreCase(reuqest.getQueryScene())
            && organizationApollo.enableApproveShowAllOrg()){
            return new JSONResult<>(listOrgTreeAndSort(mbOrgInfoList, null, true, sortType));
        }
        if(APPROVE.toString().equalsIgnoreCase(reuqest.getQueryScene())) {
            return new JSONResult<>(listOrgTreeAndSort(mbOrgInfoList, goalOrgId, true, sortType));
        }
        // 是否要展示此组织id的根组织的所有组织树信息
        if (StrUtil.isNotEmpty(goalOrgId) && BooleanUtils.isTrue(reuqest.getIsShowRootOrgAllTree())) {
            String rootOrgId = OrganizationUtil.getRootOrgId(mbOrgInfoList, goalOrgId);
            return new JSONResult<>(listOrgTreeAndSort(mbOrgInfoList, rootOrgId, true, sortType));
        }
        if (StrUtil.isNotEmpty(goalOrgId)) {
            return new JSONResult<>(listOrgTreeAndSort(mbOrgInfoList, goalOrgId, ifShowChildCompany, sortType));
        }
        // #1.后台用户，查询所有组织结构
        if (bgUser) {
            return new JSONResult<>(listOrgTreeAndSort(mbOrgInfoList, null, ifShowChildCompany, sortType));
        }
        String orgId = null;
        // #2.不是后台用户
        // #2.1需要从最近公司开始展示树
        if (ifStartWithCompany == null || ifStartWithCompany) {
            orgId = baseUserInfo.getCorpId();
        } else {
            // #2.2不需要从最近公司开始展示树
            orgId = baseUserInfo.getOrgId();
        }
        return new JSONResult<>(listOrgTreeAndSort(mbOrgInfoList, orgId, ifShowChildCompany, sortType));
    }

    /**
     * 查询所有组织树并且排序
     */
    private List<GetOrgTreeResponse> listOrgTreeAndSort(List<MbOrgInfo> mbOrgInfoList, String orgId,
        Boolean ifShowChildCompany, String sortType) {
        List<GetOrgTreeResponse> orgList = OrganizationUtil.listOrgTree(mbOrgInfoList, orgId, ifShowChildCompany);
        if (SortTypeEnum.BY_NAME_ASC.name().equals(sortType)) {
            Collator comparator = Collator.getInstance(Locale.CHINA);
            sortByComparatorAsc(orgList, comparator);
        }
        return orgList;
    }

    /**
     * 按比较器顺序排序
     *
     * @param orgList 组织信息列表
     * @param comparator 比较器
     */
    private void sortByComparatorAsc(List<GetOrgTreeResponse> orgList, Collator comparator) {
        orgList.sort((o1, o2) -> comparator.compare(o1.getLabel(), o2.getLabel()));
        for (GetOrgTreeResponse org : orgList) {
            if (CollectionUtils.isEmpty(org.getChildren())) {
                continue;
            }
            sortByComparatorAsc(org.getChildren(), comparator);
        }
    }

    /**
     * 根据当前数据权限查询组织树
     * 前端接口
     *
     * @return
     */
    @RequestMapping("/listOrgTree")
    @ResponseBody
    public JSONResult<List<GetOrgTreeResponse>> listOrgTree(@RequestBody ListOrgTreeRequest listOrgTreeRequest, BaseUserInfo baseUserInfo) {
        listOrgTreeRequest.setCorpId("");
        List<GetOrgTreeResponse> getOrgTreeResponses = CollUtil.newArrayList();
        // 查询用户信息，判断是否是后台员工
        Boolean bgUser = baseUserInfo.getBgUser();
        Boolean ifShowChildCompany = listOrgTreeRequest.getIfShowChildCompany();
        MbOrgInfo mbOrgInfo = null;
        // 查询所有组织结构
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAll();
        if (listOrgTreeRequest.getIsShowCompany() != null && listOrgTreeRequest.getIsShowCompany()) {
            mbOrgInfoList = mbOrgInfoList.stream().filter(i -> Objects.equals(i.getOrgType(), "C")).collect(Collectors.toList());
        }
        // 是否开启全集团查询 true:查询全集团数据, false:查询公司数据  , 开启全集团查询就不受数据权限控制
        boolean findWholeGroup = WholeGroupQueryEnum.APPROVE.getCode().equals(listOrgTreeRequest.getWholeGroupQuery())
                && organizationApollo.enableApproveShowAllOrg();
        // #1.后台用户，查询所有组织结构
        /**
         *  前台用户查询  如果配置了数据权限则直接根据数据权限走      如果未配置数据权限则默认取当前用户所在公司得数据不穿透子公司
         */
        if (baseUserInfo.getDataPermissionControl() && !findWholeGroup) {
            ResourceInfo resourceInfo = manager.getResource(String.valueOf(baseUserInfo.getRoleId()), ResourceInfo.class);
            List<ResourceInfo.DeptInfo> deptInfos = resourceInfo.getDeptInfos();

            mbOrgInfoList = getMbOrgInfoList(mbOrgInfoList, deptInfos);

            Map<String, List<MbOrgInfo>> parentIdMap = mbOrgInfoList.stream()
                    .filter(p -> StringUtils.isNotBlank(p.getParentId()))
                    .collect(Collectors.groupingBy(MbOrgInfo::getParentId));
            log.info("前台用户,角色信息:{}数据权限:{}", baseUserInfo.getRoleId(), JsonUtils.toJsonString(mbOrgInfoList));
            getOrgTreeResponses = resourceDataMappingTree(mbOrgInfoList, parentIdMap);
        } else if ((!bgUser && !baseUserInfo.getDataPermissionControl()) || findWholeGroup) {
            getOrgTreeResponses = getGetOrgTreeResponses(findWholeGroup,listOrgTreeRequest, mbOrgInfoList, ifShowChildCompany);
            log.info("前台用户,没有数据管控,baseUserInfo:{},getOrgTreeResponses:{}",JsonUtils.toJsonString(baseUserInfo),JsonUtils.toJsonString(getOrgTreeResponses));
        } else {
            if (StringUtils.isNotBlank(listOrgTreeRequest.getCorpId())) {
                mbOrgInfoList = mbOrgInfoList.stream().filter(a -> a.getId() > 0).collect(Collectors.toList());
            }
            getOrgTreeResponses = getGetOrgTreeResponses(findWholeGroup,listOrgTreeRequest, mbOrgInfoList, ifShowChildCompany);
            log.info("后台用户,没有数据管控,baseUserInfo:{},getOrgTreeResponses:{}",JsonUtils.toJsonString(baseUserInfo),JsonUtils.toJsonString(getOrgTreeResponses));
        }
        //用于角色配置页面   选择组织树回显功能
        if (!Objects.isNull(listOrgTreeRequest.getRoleId())) {
            ResourceInfo resourceInfo = roleResourceService.getResourceData(listOrgTreeRequest.getRoleId());
            List<ResourceInfo.DeptInfo> deptInfos = resourceInfo.getDeptInfos();
            Set<Long> deptId = Optional.ofNullable(deptInfos).orElse(new ArrayList<>()).stream().map(ResourceInfo.DeptInfo::getId).collect(Collectors.toSet());
            getOrgTreeResponses = checkDeptisAddRole(getOrgTreeResponses, deptId);
        }

        //增加排序默认部门放最后
        for (GetOrgTreeResponse response : getOrgTreeResponses) {
            sortOrgTree(response);
        }

        //组织名称是否展示(本级)文案
        if (listOrgTreeRequest.isShowLevelText()) {
            setLevelText(getOrgTreeResponses);
        }
        log.info("返回结果,getOrgTreeResponses:{}",JsonUtils.toJsonString(getOrgTreeResponses));
        return new JSONResult<>(getOrgTreeResponses);
    }

    /**
     * 根据开关判断获取全集团查询数据
     * @param listOrgTreeRequest
     * @param mbOrgInfoList
     * @param ifShowChildCompany
     * @return
     */
    private List<GetOrgTreeResponse> getGetOrgTreeResponses(boolean findWholeGroup,ListOrgTreeRequest listOrgTreeRequest, List<MbOrgInfo> mbOrgInfoList, Boolean ifShowChildCompany) {
        List<GetOrgTreeResponse> getOrgTreeResponses;
        if(findWholeGroup){
            getOrgTreeResponses = OrganizationUtil.listOrgTree(mbOrgInfoList, null, ifShowChildCompany);
        } else {
            getOrgTreeResponses = OrganizationUtil.listOrgTree(mbOrgInfoList, listOrgTreeRequest.getCorpId(), ifShowChildCompany);
        }
        return getOrgTreeResponses;
    }

    private void setLevelText(List<GetOrgTreeResponse> getOrgTreeResponses) {
        for (GetOrgTreeResponse getOrgTreeRespons : getOrgTreeResponses) {
            if (CollectionUtils.isNotEmpty(getOrgTreeRespons.getChildren())) {
                GetOrgTreeResponse convert = JsonUtils.convert(getOrgTreeRespons, GetOrgTreeResponse.class);
                convert.setLabel(convert.getLabel() + " (本级)");
                convert.setChildren(null);
                getOrgTreeRespons.getChildren().add(0, convert);
                setLevelText(getOrgTreeRespons.getChildren());
            }
        }
    }

    @RequestMapping("/listOrgTreeDepartment")
    public JSONResult<List<GetOrgTreeResponse>> listOrgTreeDepartment(@RequestBody ListOrgTreeRequest listOrgTreeRequest, BaseUserInfo baseUserInfo) {
        ResourceInfo resourceInfo = manager.getResource(String.valueOf(baseUserInfo.getRoleId()), ResourceInfo.class);
        List<ResourceInfo.DeptInfo> deptInfos = resourceInfo.getDeptInfos();
        if (CollectionUtils.isNotEmpty(deptInfos)){
            Map<String, ResourceInfo.DeptInfo> resourceMap = deptInfos.stream().collect(Collectors.toMap(item -> item.getOrgId(), Function.identity(), (k1, k2) -> k1));
            List<MbOrgInfo> mbOrgInfos = organizationInfoService.listAllDepartments(listOrgTreeRequest.getCorpId(), false);
            if (CollectionUtils.isEmpty(mbOrgInfos)){
                return JSONResult.ok();
            }
            List<MbOrgInfo> filterOrgList = new ArrayList<>(mbOrgInfos.size());
            for (MbOrgInfo orgInfo:mbOrgInfos){
                ResourceInfo.DeptInfo deptInfo = resourceMap.get(orgInfo.getOrgId());
                if (Objects.isNull(deptInfo)){
                    continue;
                }
                filterOrgList.add(orgInfo);
            }
            Map<String, List<MbOrgInfo>> parentIdMap = mbOrgInfos.stream().filter(p -> StringUtils.isNotBlank(p.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
            return new JSONResult<>(resourceDataMappingTree(filterOrgList, parentIdMap));
        } else {
            GetOrgTreeRequest getOrgTreeRequest = new GetOrgTreeRequest(listOrgTreeRequest.getCorpId(), false, false, false);
            GetOrgTreeRsp orgTree = organizationInfoService.getOrgTree(getOrgTreeRequest);
            if (Objects.isNull(orgTree)){
                return JSONResult.ok();
            }
            return new JSONResult<>(Lists.newArrayList(JsonUtils.convert(orgTree, GetOrgTreeResponse.class)));
        }
    }

    private List<MbOrgInfo> getMbOrgInfoList(List<MbOrgInfo> mbOrgInfoList, List<ResourceInfo.DeptInfo> org) {
        List<MbOrgInfo> mbOrgInfos = new ArrayList<>();
        if (org.stream().allMatch(deptInfo -> !Objects.equals(OrgTypeEnum.D.getCode(), deptInfo.getOrgType()))) {

            for (ResourceInfo.DeptInfo deptInfo : org) {
                Map<String, List<MbOrgInfo>> parentIdMapList = mbOrgInfoList.stream().filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getParentId())).collect(Collectors.groupingBy(MbOrgInfo::getParentId));
                List<String> departmentIds = CollUtil.newArrayList();
                listAllDepartmentIdsByCompanyId(deptInfo.getOrgId(), parentIdMapList, departmentIds);
                List<MbOrgInfo> result = mbOrgInfoList.stream().filter(o -> departmentIds.contains(o.getOrgId()) || Objects.equals(o.getOrgId(), deptInfo.getOrgId())).collect(Collectors.toList());

                mbOrgInfos.addAll(result);
            }
            return mbOrgInfos;
        }
        mbOrgInfos = mbOrgInfoList.stream().filter(x -> org.stream().map(ResourceInfo.DeptInfo::getOrgId).collect(Collectors.toSet()).contains(x.getOrgId())).collect(Collectors.toList());
        return mbOrgInfos.stream().distinct().collect(Collectors.toList());
    }

    private void listAllDepartmentIdsByCompanyId(String parentId, Map<String, List<MbOrgInfo>> parentIdMapList, List<String> departmentIds) {
        List<MbOrgInfo> mbOrgInfoList = parentIdMapList.get(parentId);
        if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
            for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
                if (mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT)) {
                    departmentIds.add(mbOrgInfo.getOrgId());
                    listAllDepartmentIdsByCompanyId(mbOrgInfo.getOrgId(), parentIdMapList, departmentIds);
                }
            }
        }
    }

    private void sortOrgTree(GetOrgTreeResponse response) {
        if (CollectionUtils.isNotEmpty(response.getChildren())) {
            response.getChildren().sort(Comparator.comparing(GetOrgTreeResponse::getOId).reversed());
        }
    }

    /**
     * 查询所有组织树
     *
     * @return
     */
    @RequestMapping("/getOrgTreePlus")
    public JSONResult<List<GetOrgTreeRsp>> getOrgTreePlus(@RequestBody GetOrgTreeReq request) {
        //查询所有组织
        List<MbOrgInfo> orgInfoAll = mbOrgInfoMapper.listAll();
        List<MbOrgInfo> filterOrgList = null;

        if (StringUtils.isBlank(request.getOrgId())) {
            request.setIsErgodic(true);
            request.setIsSelectUser(false);
            filterOrgList = orgInfoAll.stream().filter(item -> StringUtils.isBlank(item.getParentId())).collect(Collectors.toList());
        } else {
            filterOrgList = orgInfoAll.stream().filter(item -> item.getOrgId().equals(request.getOrgId())).collect(Collectors.toList());
        }

        if (CollectionUtils.isEmpty(filterOrgList)) {
            return new JSONResult<>(new ArrayList<>());
        }

        List<GetOrgTreeRsp> result = new ArrayList<>();
        filterOrgList.forEach(item -> {
            GetOrgTreeRequest getOrgTreeRequest = new GetOrgTreeRequest(item.getOrgId(), request.getIsSelectUser(), request.getIsErgodic(), request.getIsShowDefaultOrg());
            GetOrgTreeRsp orgTree = organizationInfoService.getOrgTree(getOrgTreeRequest);
            if (orgTree != null) {
                result.add(orgTree);
            }
        });
        return new JSONResult<>(result);
    }

    @RequestMapping("/getOrgTree")
    public JSONResult<List<GetOrgTreeRsp>> getOrgTree(@RequestBody GetOrgTreeRequest request) {
        GetOrgTreeRsp orgTree = organizationInfoService.getOrgTree(request);
        List<GetOrgTreeRsp> result = new ArrayList<>();
        result.add(orgTree);
        return new JSONResult<>(result);
    }

    /**
     * 封装树返回值
     *
     * @param
     * @param parentIdMap
     */
    private List<GetOrgTreeResponse> resourceDataMappingTree(List<MbOrgInfo> mbOrgInfos, Map<String, List<MbOrgInfo>> parentIdMap) {
        List<GetOrgTreeResponse> responses = new ArrayList<>();

        Map<String, MbOrgInfo> orgMap = mbOrgInfos.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, item -> item, (k1, k2) -> k1));

        List<MbOrgInfo> topLevelList = Lists.newArrayList();
        mbOrgInfos.stream().forEach(i -> {
            //顶级集团无parentID
            if (StringUtils.isBlank(i.getParentId())) {
                topLevelList.add(i);
                return;
            }
            //匹配顶级组织信息  parentIdMap 里面有当前组织 且  当前组织父级不在当前集合中   则当前组织为最大节点
            if (CollectionUtils.isNotEmpty(parentIdMap.get(i.getOrgId())) && Objects.isNull(orgMap.get(i.getParentId()))) {
                topLevelList.add(i);
                return;
            }

            //匹配顶级组织信息  parentIdMap 里面没有当前组织  且  当前组织父级也不在当前集合中  则当前节点为单节点
            if (CollectionUtils.isEmpty(parentIdMap.get(i.getOrgId())) && Objects.isNull(orgMap.get(i.getParentId()))) {
                topLevelList.add(i);
            }
        });
        if (CollectionUtils.isEmpty(topLevelList)) {
            topLevelList.addAll(mbOrgInfos);
        }

        // 顶级集团数据
        for (MbOrgInfo mbOrgInfo : topLevelList) {
            List<GetOrgTreeResponse> responseList = new ArrayList<>();
            GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                    .id(mbOrgInfo.getOrgId())
                    .label(mbOrgInfo.getName())
                    .pid(mbOrgInfo.getParentId())
                    .level(mbOrgInfo.getLevel())
                    .type(mbOrgInfo.getOrgType())
                    .orgId(mbOrgInfo.getOrgId())
                    .type(mbOrgInfo.getOrgType())
                    .valid(mbOrgInfo.getValid())
                    .oId(mbOrgInfo.getId())
                    .businessCode(mbOrgInfo.getBusinessCode())
                    .parentBusinessCode(mbOrgInfo.getParentBusinessCode())
                    .build();
            // 递归查找子级组织
            GetOrgTreeResponse orgTreeResponse = resourceDataMappingTree(getOrgTreeResponse, parentIdMap, responseList);
            responses.add(orgTreeResponse);
        }
        return responses;
    }

    public GetOrgTreeResponse resourceDataMappingTree(GetOrgTreeResponse treeNode, Map<String, List<MbOrgInfo>> parentIdMap, List<GetOrgTreeResponse> responses) {
        List<MbOrgInfo> mbOrgInfos = parentIdMap.get(treeNode.getOrgId());
        if (CollectionUtils.isEmpty(mbOrgInfos)) {
            mbOrgInfos = parentIdMap.get(treeNode.getId());
        }
        if (CollectionUtils.isNotEmpty(mbOrgInfos)) {
            if (CollectionUtils.isEmpty(treeNode.getChildren())) {
                List<GetOrgTreeResponse> children = new ArrayList<>(mbOrgInfos.size());
                treeNode.setChildren(children);
            }
            List<GetOrgTreeResponse> children = treeNode.getChildren();
            // 排序，公司在前，部门在后
            List<MbOrgInfo> companyList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()) && mbOrgInfo.getOrgType().equals(OrganizationConst.COMPANY))
                    .collect(Collectors.toList());
            List<MbOrgInfo> departmentList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()) && mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT))
                    .collect(Collectors.toList());
            List<MbOrgInfo> sortedList = new ArrayList<>(companyList.size() + departmentList.size());
            sortedList.addAll(companyList);
            sortedList.addAll(departmentList);
            for (MbOrgInfo mbOrgInfo : sortedList) {
                // 组装返回数据
                GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                        .id(mbOrgInfo.getOrgId())
                        .label(mbOrgInfo.getName())
                        .pid(mbOrgInfo.getParentId())
                        .level(mbOrgInfo.getLevel())
                        .type(mbOrgInfo.getOrgType())
                        .orgId(mbOrgInfo.getOrgId())
                        .valid(mbOrgInfo.getValid())
                        .oId(mbOrgInfo.getId())
                        .businessCode(mbOrgInfo.getBusinessCode())
                        .parentBusinessCode(mbOrgInfo.getParentBusinessCode())
                        .build();
                // 如果当前层级为部门，也就是orgType为D的话，再将D对应orgId查询员工表，将员工表中间org_id等于当前部门id的人查询出来，插入进去
                children.add(resourceDataMappingTree(getOrgTreeResponse, parentIdMap, responses));
            }
            treeNode.setChildren(children);
        }
        return treeNode;
    }

    private List<GetOrgTreeResponse> checkDeptisAddRole(List<GetOrgTreeResponse> getOrgTreeResponses, Set<Long> deptId) {
        if (CollectionUtils.isEmpty(getOrgTreeResponses)) {
            return null;
        }
        getOrgTreeResponses.stream().forEach(d -> {
            if (deptId.contains(d.getOId())) {
                d.setAdd("T");
            } else {
                d.setAdd("F");
            }
            d.setChildren(checkDeptisAddRole(d.getChildren(), deptId));
        });
        return getOrgTreeResponses;
    }


    /**
     * 封装树返回值
     *
     * @param mbOrgInfo
     * @param parentIdMap
     */
    private GetOrgTreeResponse pageckgeData(MbOrgInfo mbOrgInfo, Map<String, List<MbOrgInfo>> parentIdMap) {
        GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                .id(mbOrgInfo.getOrgId())
                .label(mbOrgInfo.getName())
                .pid(mbOrgInfo.getParentId())
                .level(mbOrgInfo.getLevel())
                .type(mbOrgInfo.getOrgType())
                .orgId(mbOrgInfo.getOrgId())
                .type(mbOrgInfo.getOrgType())
                .valid(mbOrgInfo.getValid())
                .build();
        // 递归查找子级组织
        findChildren(getOrgTreeResponse, parentIdMap);
        return getOrgTreeResponse;
    }

    private GetOrgTreeResponse pageckgeDataWithoutCompany(MbOrgInfo mbOrgInfo, Map<String, List<MbOrgInfo>> parentIdMap) {
        GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                .id(mbOrgInfo.getOrgId())
                .label(mbOrgInfo.getName())
                .pid(mbOrgInfo.getParentId())
                .level(mbOrgInfo.getLevel())
                .type(mbOrgInfo.getOrgType())
                .orgId(mbOrgInfo.getOrgId())
                .type(mbOrgInfo.getOrgType())
                .valid(mbOrgInfo.getValid())
                .build();
        // 递归查找子级组织
        findChildrenWithoutCompany(getOrgTreeResponse, parentIdMap);
        return getOrgTreeResponse;
    }

    /**
     * 根据父级查找所有子级，按照level划分
     *
     * @param parentId     父级id
     * @param companyMap   按照parentId划分的组织结构map
     * @param levelListMap 最终返回map，按照level划分的
     */
    private void findChildrenByParentId(String
                                                parentId, Map<String, List<MbOrgInfo>> companyMap, Map<Integer, List<MbOrgInfo>> levelListMap) {
        List<MbOrgInfo> mbOrgInfoList = companyMap.get(parentId);
        if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
            for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
                Integer level = mbOrgInfo.getLevel();
                List<MbOrgInfo> levelList = levelListMap.get(level);
                if (CollectionUtils.isEmpty(levelList)) {
                    levelList = new ArrayList<>();
                }
                levelList.add(mbOrgInfo);
                levelListMap.put(mbOrgInfo.getLevel(), levelList);
                findChildrenByParentId(mbOrgInfo.getOrgId(), companyMap, levelListMap);
            }
            System.out.println(levelListMap);
        }
    }

    /**
     * 修改组织架构联系人信息
     *
     * @param updateContactInfoRequest
     * @return
     */
    @RequestMapping("/updateContactInfo")
    public JSONResult<Boolean> updateContactInfo(@RequestBody @Valid UpdateContactInfoRequest updateContactInfoRequest) {
        MbOrgInfo mbOrgInfo = new MbOrgInfo();
        mbOrgInfo.setOrgId(updateContactInfoRequest.getOrgId());
        mbOrgInfo.setContactEmail(updateContactInfoRequest.getContactEmail());
        mbOrgInfo.setContactName(updateContactInfoRequest.getContactPeople());
        mbOrgInfo.setContactPhone(updateContactInfoRequest.getContactPhone());
        mbOrgInfo.setContactAreaCode(updateContactInfoRequest.getAreaCode());
        boolean update = organizationInfoService.updateContactInfo(mbOrgInfo);
        return new JSONResult<>(update);
    }

    /**
     * 修改组织结构支付方式
     *
     * @param updatePayTypeRequest
     * @return
     */
    @RequestMapping("/updatePayType")
    public JSONResult<Boolean> updatePayType(@RequestBody @Valid UpdatePayTypeRequest updatePayTypeRequest) {
        String businessOrigin = updatePayTypeRequest.getBusinessOrigin();
        // 供应商审核通过修改支付方式
        if (StrUtil.isNotBlank(businessOrigin) && StrUtil.equals(businessOrigin, "supplier")) {
            return updatePayTypeForSupplier(updatePayTypeRequest);
        }
        List<String> orgIds = updatePayTypeRequest.getOrgId();
        String payType = updatePayTypeRequest.getPayType();
        // 公司id
        String corpId = updatePayTypeRequest.getCorpId();
        if (StrUtil.isNotBlank(corpId)) {
            List<String> departmentIds = organizationInfoService.listAllDepartmentByOrgId(corpId);
            clearOrgFlightAndTrainSitePayType(departmentIds);
        }
        if (CollUtil.isNotEmpty(orgIds)) {
            // 修改支付方式
            updateOrgFlightAndTrainSitePayType(orgIds, payType);
        }
        return new JSONResult<>(Boolean.TRUE);
    }

    private void clearOrgFlightAndTrainSitePayType(List<String> orgIds) {
        // 将公司下的机票、火车票产线，统一支付方式的数据删除，然后再将新的保存
        boolean fFlag = orgPayTypeService.setPPayByOrgIds(orgIds, null, SiteEnum.FLIGHT.getCode(), null);
        log.info("国内机票支付方式充值[{}]", JsonUtils.toJsonString(orgIds));
        boolean tFlag = orgPayTypeService.setPPayByOrgIds(orgIds, null, SiteEnum.TRAIN.getCode(), null);
        log.info("火车票支付方式充值[{}]", JsonUtils.toJsonString(orgIds));
    }

    /**
     * @param updatePayTypeRequest
     * @return
     */
    private JSONResult<Boolean> updatePayTypeForSupplier(UpdatePayTypeRequest updatePayTypeRequest) {
        List<String> orgIds = updatePayTypeRequest.getOrgId();
        String payType = updatePayTypeRequest.getPayType();
        // 公司id
        String corpId = updatePayTypeRequest.getCorpId();
        if (StrUtil.isNotBlank(corpId)) {
            // 找到公司下所有部门
            List<String> departmentIds = organizationInfoService.listAllDepartmentByOrgId(corpId);
            // 批量更新
            orgPayTypeService.batchUpdate(departmentIds, payType, SiteEnum.HOTEL.getCode());
            log.info("修改酒店支付方式[{}],组织[{}]", payType, departmentIds);
        }
        if (CollUtil.isNotEmpty(orgIds)) {
            // 修改支付方式
            updateOrgFlightAndTrainSitePayType(orgIds, payType);
            // 开启组织架构的机火统一支付开关
            organizationInfoService.batchUpdateOpenUnitePayment(orgIds, true);
        }
        return new JSONResult<>(Boolean.TRUE);
    }

    /**
     * 修改机票和火车票的支付方式
     *
     * @param orgIds
     * @param payType
     * @return
     */
    private Boolean updateOrgFlightAndTrainSitePayType(List<String> orgIds, String payType) {
        boolean fResult = orgPayTypeService.batchUpdate(orgIds, payType, SiteEnum.FLIGHT.getCode());
        log.info("国内机票设置支付方式成功[{}]", orgIds);
        boolean tResult = orgPayTypeService.batchUpdate(orgIds, payType, SiteEnum.TRAIN.getCode());
        log.info("火车票设置支付方式成功[{}]", orgIds);
        return Boolean.TRUE;
    }

    /**
     * 查询orgId查询组织所在直属子公司信息
     *
     * @param orgId 组织结构id
     * @return 子公司信息
     */
    @RequestMapping(value = "/findRecentCompanyInfoByOrgId")
    public JSONResult<OrgInfoVo> findRecentCompanyInfoByOrgId(@RequestParam(value = "orgId") String orgId) {
        MbOrgInfo mbOrgInfo = organizationInfoService.findRecentCompanyIdByOrgId(orgId);
        OrgInfoVo orgInfoVo = new OrgInfoVo();
        if (mbOrgInfo != null) {
            BeanUtils.copyProperties(mbOrgInfo, orgInfoVo);
        }
        return new JSONResult<>(orgInfoVo);
    }

    /**
     * 模糊搜索组织结构信息
     *
     * @param findOrgByNameRequest
     * @return
     */
    @RequestMapping("/fuzzyOrgByName")
    public JSONResult<List<FindOrgByNameResponse>> fuzzyOrgByName(@RequestBody FindOrgByNameRequest findOrgByNameRequest) {
        String keyWord = findOrgByNameRequest.getKeyWord();
        List<MbOrgInfo> orgList = organizationInfoService.fuzzyByName(keyWord);
        if (CollUtil.isEmpty(orgList)) {
            return new JSONResult<>(CollUtil.newArrayList());
        }
        List<FindOrgByNameResponse> returnList = CollUtil.newArrayList();
        for (MbOrgInfo mbOrgInfo : orgList) {
            FindOrgByNameResponse findOrgByNameResponse = new FindOrgByNameResponse();
            findOrgByNameResponse.setCorpId(mbOrgInfo.getOrgId());
            findOrgByNameResponse.setName(mbOrgInfo.getName());
            findOrgByNameResponse.setId(mbOrgInfo.getId());
            findOrgByNameResponse.setType(mbOrgInfo.getOrgType());
            returnList.add(findOrgByNameResponse);
        }
        return new JSONResult<>(returnList);
    }

    /**
     * 模糊搜索组织结构信息
     */
    @RequestMapping("/fuzzyOrgByNameAndType")
    public JSONResult<List<FindOrgByNameAndTypeResponse>> fuzzyOrgByNameAndType(@RequestBody FindOrgByNameAndTypeRequest request, BaseUserInfo userInfo) {
        if (StringUtils.isBlank(request.getOrgId()) && userInfo.getBgUser() != null && !userInfo.getBgUser()) {
            log.info("前台用户登录，设置corpId");
            request.setOrgId(userInfo.getCorpId());
        }
        List<MbOrgInfo> orgList;
        if (StringUtils.isBlank(request.getOrgId())) {
            orgList = organizationInfoService.fuzzyByNameAndType(request.getKeyWord(), request.getOrgType());
        } else {
            log.info("模糊搜索组织下的部门信息，不穿透子公司");
            orgList = organizationInfoService.listAllDepartments(request.getOrgId(), true);
            orgList = orgList.stream().filter(o -> o.getName() != null && o.getName().contains(request.getKeyWord())).collect(Collectors.toList());
        }
        if (CollUtil.isEmpty(orgList)) {
            return new JSONResult<>(CollUtil.newArrayList());
        }

        // 所属角色的数据权限校验。只返回数据权限内的组织。如果为空则是admin用户，返回所有组织
        Object o = RequestContext.getCurrentContext().get(DATA_PERMISSION_ORG_ID_LIST);
        if (o != null) {
            orgList = orgList.stream()
                    // assert org instanceof List<String>
                    .filter(org -> ((List<String>) o).contains(org.getOrgId()))
                    .collect(Collectors.toList());
        }

        List<FindOrgByNameAndTypeResponse> returnList = CollUtil.newArrayList();
        for (MbOrgInfo mbOrgInfo : orgList) {
            FindOrgByNameAndTypeResponse response = new FindOrgByNameAndTypeResponse();
            response.setOrgId(mbOrgInfo.getOrgId());
            response.setOrgName(mbOrgInfo.getName());
            response.setOrgType(mbOrgInfo.getOrgType());
            returnList.add(response);
        }
        return new JSONResult<>(returnList);
    }

    /**
     * 分页获取类型为公司的组织
     *
     * @return
     */
    @RequestMapping(value = "/getAllCompany")
    JSONResult<GetAllCompanyResponse> getAllCompany(@RequestBody GetAllCompanyRequest getAllCompanyRequest) {
        Integer pageNum = getAllCompanyRequest.getPageNum();
        Integer pageSize = getAllCompanyRequest.getPageSize();
        List<MbOrgInfo> orgInfoList = organizationInfoService.listAllCompany(pageSize, pageNum);
        GetAllCompanyResponse getAllCompanyResponse = new GetAllCompanyResponse();
        if (CollUtil.isNotEmpty(orgInfoList)) {
            List<OrgInfoVo> orgInfoVos = CollUtil.newArrayList();
            for (MbOrgInfo mbOrgInfo : orgInfoList) {
                OrgInfoVo orgInfoVo = new OrgInfoVo();
                orgInfoVo.setOrgId(mbOrgInfo.getOrgId());
                orgInfoVo.setName(mbOrgInfo.getName());
                orgInfoVos.add(orgInfoVo);
            }
            getAllCompanyResponse.setOrgInfoVos(orgInfoVos);
        }
        return new JSONResult<>(getAllCompanyResponse);
    }

    /**
     * 分页获取类型为公司的组织
     *
     * @return
     */
    @RequestMapping(value = "/getAllCompanyWithDeleted")
    JSONResult<GetAllCompanyResponse> getAllCompanyWithDeleted(@RequestBody GetAllCompanyRequest getAllCompanyRequest) {
        Integer pageNum = getAllCompanyRequest.getPageNum();
        Integer pageSize = getAllCompanyRequest.getPageSize();
        List<MbOrgInfo> orgInfoList = organizationInfoService.listAllCompanyWithDeleted(pageSize, pageNum);
        GetAllCompanyResponse getAllCompanyResponse = new GetAllCompanyResponse();
        if (CollUtil.isNotEmpty(orgInfoList)) {
            List<OrgInfoVo> orgInfoVos = CollUtil.newArrayList();
            for (MbOrgInfo mbOrgInfo : orgInfoList) {
                OrgInfoVo orgInfoVo = new OrgInfoVo();
                orgInfoVo.setOrgId(mbOrgInfo.getOrgId());
                orgInfoVo.setName(mbOrgInfo.getName());
                orgInfoVos.add(orgInfoVo);
            }
            getAllCompanyResponse.setOrgInfoVos(orgInfoVos);
        }
        return new JSONResult<>(getAllCompanyResponse);
    }

    /**
     * 获取登录人本人常旅客信息
     *
     * @return
     */
    @PostMapping("/ffp/ffpUser")
    public JSONResult ffpUser(@RequestBody FfpRequest ffpRequest, BaseUserInfo baseUserInfo) {
        JSONResult<FfpPageVo> ffpItemsResult = organizationInfoService.getFfpItems(ffpRequest, baseUserInfo);
        if (ffpItemsResult.isSUCCESS() && ffpItemsResult.getData() != null) {
            List<FfpVo> ffpVos = (List<FfpVo>) ffpItemsResult.getData().getPlist();
            log.info("ffpUser->ffpVos:{}", JsonUtils.toJsonString(ffpVos));
            if (!CollectionUtils.isEmpty(ffpVos)) {
                Optional<FfpVo> first = ffpVos.stream().filter(item -> item.isIsOwnner()==true).findFirst();
                if (first.isPresent()){
                    return JSONResult.success(first.get());
                }
            }
        }
        return JSONResult.success(new FfpVo());
    }

    /**
     * 常旅分页列表
     *
     * @param ffpRequest   ffpRequest
     * @param baseUserInfo baseUserInfo
     * @return JSONResult
     */
    @PostMapping("/ffp/page")
    public JSONResult ffpPages(@RequestBody FfpRequest ffpRequest, BaseUserInfo baseUserInfo) {
        return organizationInfoService.getFfpItems(ffpRequest, baseUserInfo);
    }

    @RequestMapping("/ffp/getFfBasicsInfo")
    public JSONResult<List<GetFfBasicsInfoResponse>> getFfBasicsInfo(@RequestParam String uid) {
        return JSONResult.success(organizationInfoService.getFfBasicsInfo(uid));
    }

    /**
     * 新增常旅信息
     */
    @PostMapping("ffp/add")
    public JSONResult ffpAdd(@Valid @RequestBody FfpAddRequest ffpAddRequest, BaseUserInfo baseUserInfo) {
        return organizationInfoService.saveFfpItem(ffpAddRequest, baseUserInfo);
    }

    @PostMapping("ffp/modify")
    public JSONResult ffpModify(@Valid @RequestBody FfpModifyRequest ffpModifyRequest, BaseUserInfo baseUserInfo) {
        return organizationInfoService.modifyFfpItem(ffpModifyRequest, baseUserInfo);
    }

    /**
     * 删除常旅信息
     *
     * @param ffpIdRequest ffpIdRequest
     * @return JSONResult
     */
    @PostMapping("ffp/delete")
    public JSONResult ffpDelete(@Valid @RequestBody FfpIdRequest ffpIdRequest) {
        return organizationInfoService.deleteFfpItem(ffpIdRequest);
    }

    /**
     * 通过子公司id查询子公司下直属部门信息，子公司下的子公司不包括
     * http://localhost:7890/org/listDepartmentByCompanyIdAndName?companyId=3&name=
     *
     * @param companyId 子公司id(也就是组织结构id)
     * @param name      名称不为空的时候模糊匹配查询
     * @return 直属部门信息 id，name
     */
    @RequestMapping("/listDepartmentByCompanyIdAndName")
    public JSONResult<List<GetOrgTreeResponse>> listDepartmentByCompanyIdAndName(@RequestParam(value = "companyId") String companyId,
                                                                                 @RequestParam(value = "name", required = false) String name,
                                                                                 @RequestParam(value = "ifIncRoot", defaultValue = "false") boolean ifIncRoot) {
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAll();
        Map<String, List<MbOrgInfo>> parentListMap = new HashMap<>();
        GetOrgTreeResponse getOrgTreeResponse = new GetOrgTreeResponse();
        getOrgTreeResponse.setOrgId(companyId);
        for (MbOrgInfo mbOrgInfo : mbOrgInfoList) {
            if (Objects.equals(mbOrgInfo.getOrgId(), companyId)) {
                getOrgTreeResponse.setId(String.valueOf(mbOrgInfo.getId()));
                getOrgTreeResponse.setLabel(mbOrgInfo.getName());
                getOrgTreeResponse.setType(mbOrgInfo.getOrgType());
                getOrgTreeResponse.setValid(mbOrgInfo.getValid());
                getOrgTreeResponse.setPid(mbOrgInfo.getParentId());
            }
            if (mbOrgInfo.getParentId() == null) {
                continue;
            }
            parentListMap.putIfAbsent(mbOrgInfo.getParentId(), new ArrayList<>());
            parentListMap.get(mbOrgInfo.getParentId()).add(mbOrgInfo);
        }
        // 构建以当前companyId起始的tree
        findChildren(getOrgTreeResponse, parentListMap);
        // 树移除掉公司和name不匹配的
        List<GetOrgTreeResponse> list = removeCompanyAndFuzzyName(getOrgTreeResponse, name);
        getOrgTreeResponse.setChildren(list);
//        if (ifIncRoot && getOrgTreeResponse.getType().equalsIgnoreCase(OrganizationConst.COMPANY)) {
//            list.add(getOrgTreeResponse);
//        }
        return new JSONResult<>(Lists.newArrayList(getOrgTreeResponse));
    }

    /**
     * 通过uid查询所有直属父级部门（一直到顶级子公司）
     * http://localhost:7890/org/findAllParentIdByOrgId?orgId=7
     *
     * @param orgId 组织结构id
     * @return 所有
     */
    @RequestMapping("/findAllParentIdByOrgId")
    public List<String> findAllParentIdByOrgId(String orgId) {
        List<OrgInfoVo> orgInfoList = organizationInfoService.getOrgInfoList(orgId, true);
        List<String> returnList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orgInfoList)) {
            returnList = orgInfoList.stream().sorted(Comparator.comparing(OrgInfoVo::getLevel).reversed())
                    .map(OrgInfoVo::getOrgId)
                    .collect(Collectors.toList());
        }
        return returnList;
    }

    /**
     * 模糊查询公司By Name
     *
     * @param name
     * @return
     */
    @GetMapping("/companies")
    public JSONResult companies(@RequestParam(name = "name", required = false) String name,
                                @RequestParam(name = "orgType", required = false) String orgType) {
        List<CompanyVo> companyVos = organizationInfoService.getCompaniesByName(name, orgType, null);
        return JSONResult.success(companyVos);
    }

    /**
     * 模糊查询公司By Name
     *
     * @param companyRequest
     * @return
     */
    @PostMapping("/getCompanies")
    public JSONResult companies(@RequestBody CompanyRequest companyRequest, BaseUserInfo baseUserInfo) {
        String name = companyRequest.getName();
        String orgType = companyRequest.getOrgType();
        List<CompanyVo> companyVos = organizationInfoService.getCompaniesByName(name, orgType, baseUserInfo);
        return JSONResult.success(companyVos);
    }


    /**
     * 查询用户证件
     *
     * @param cardType
     * @param cardNo
     * @return
     */
    @GetMapping("/getMbOrgUserIdcard")
    public JSONResult getMbOrgUserIdcard(@RequestParam(value = "cardType", required = false) Integer cardType,
                                         @RequestParam(value = "cardNo", required = false) String cardNo) {
        return JSONResult.success(iOrgUserIdCardService.selectCardInfo(cardType, cardNo));
    }

    /**
     * 初始化支付方式
     * localhost:8889/corpApi/organization/org/initPayType
     *
     * @param initPayTypeRequest
     * @return
     */
    @RequestMapping(value = "/initPayType")
    public JSONResult<Boolean> initPayType(@RequestBody InitPayTypeRequest initPayTypeRequest) {
        orgPayTypeService.initPayType(initPayTypeRequest);
        return new JSONResult<>(true);
    }

    /**
     * 酒店组织架构下配置了统一支付的组织
     * localhost:8889/corpApi/organization/org/updateHotelAccntPayType
     *
     * @param hotelAccntPayOrgRequest
     * @return
     */
    @RequestMapping(value = "/hotelAccntPayOrg")
    JSONResult<List<String>> hotelAccntPayOrg(@RequestBody HotelAccntPayOrgRequest hotelAccntPayOrgRequest) {
        String orgId = hotelAccntPayOrgRequest.getOrgId();
        String supplierId = hotelAccntPayOrgRequest.getSupplierId();
        String uid = hotelAccntPayOrgRequest.getUid();
        List<String> orgIds = organizationInfoService.listAllDepartmentByOrgId(orgId);
        CollUtil.distinct(orgIds);
        List<MbOrgPayType> mbOrgPayTypeList = orgPayTypeService.listByOrgIds(orgIds, SiteEnum.HOTEL.getCode(), PayTypeEnum.ACCNT.getType(), supplierId);
        if (CollUtil.isNotEmpty(mbOrgPayTypeList)) {
            List<String> returnList = mbOrgPayTypeList.stream().map(MbOrgPayType::getOrgId).collect(Collectors.toList());
            CollUtil.distinct(returnList);
            return new JSONResult<>(returnList);
        }
        return new JSONResult<>(CollUtil.newArrayList());
    }

    /**
     * 删除支付方式(供应商删除的时候，需要将酒店支付方式数据删除)
     *
     * @param deletePayTypeRequest
     * @return
     */
    @RequestMapping(value = "/deletePayType")
    JSONResult<Boolean> deletePayType(@Valid @RequestBody DeletePayTypeRequest deletePayTypeRequest) {
        String corpId = deletePayTypeRequest.getCorpId();
        String supplierCode = deletePayTypeRequest.getSupplierCode();
        orgPayTypeService.delete(CollUtil.newArrayList(corpId), null, SiteEnum.HOTEL.getCode(), supplierCode, Boolean.TRUE);
        return new JSONResult<>(Boolean.TRUE);
    }

    /**
     * 根据orgId批量查询组织结构信息
     */
    @RequestMapping(value = "/findByOrgIdList")
    public JSONResult<List<OrgInfoVo>> findByOrgIdList(@RequestBody List<String> orgIds) {
        if (CollectionUtils.isNotEmpty(orgIds)) {
            // 查询组织结构信息
            List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listByOrgIds(orgIds);

            if (!CollectionUtils.isEmpty(mbOrgInfoList)) {

                ArrayList<OrgInfoVo> list = Lists.newArrayList();
                mbOrgInfoList.forEach(o -> {
                    OrgInfoVo orgInfoVo = new OrgInfoVo();
                    BeanUtils.copyProperties(o, orgInfoVo);
                    list.add(orgInfoVo);
                });
                return JSONResult.success(list);
            }
            return JSONResult.errorMsg("query db return empty");
        }
        return JSONResult.errorMsg("orgIds is empty");
    }

    /**
     * 根据orgId批量查询组织结构信息包括删除的组织信息
     */
    @RequestMapping(value = "/findAllByOrgIdList")
    public JSONResult<List<OrgInfoVo>> findAllByOrgIdList(@RequestBody List<String> orgIds) {
        if (CollectionUtils.isNotEmpty(orgIds)) {
            // 查询组织结构信息
            List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAllByOrgIds(orgIds);
            if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
                ArrayList<OrgInfoVo> list = Lists.newArrayList();
                mbOrgInfoList.forEach(o -> {
                    OrgInfoVo orgInfoVo = new OrgInfoVo();
                    BeanUtils.copyProperties(o, orgInfoVo);
                    list.add(orgInfoVo);
                });
                return JSONResult.success(list);
            }
            return JSONResult.errorMsg("query db return empty");
        }
        return JSONResult.errorMsg("orgIds is empty");
    }

    /**
     * 根据orgId批量查询组织结构信息
     */
    @RequestMapping(value = "/findByIdList")
    public JSONResult<List<OrgInfoVo>> findByIdList(@RequestBody List<String> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            // 查询组织结构信息
            List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listByIds(ids);

            if (!CollectionUtils.isEmpty(mbOrgInfoList)) {

                ArrayList<OrgInfoVo> list = Lists.newArrayList();
                mbOrgInfoList.forEach(o -> {
                    OrgInfoVo orgInfoVo = new OrgInfoVo();
                    BeanUtils.copyProperties(o, orgInfoVo);
                    list.add(orgInfoVo);
                });
                return JSONResult.success(list);
            }
            return JSONResult.errorMsg("query db return empty");
        }
        return JSONResult.errorMsg("orgIds is empty");
    }


    /**
     * 查询公司发票信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/searchInvoiceInfo")
    public JSONResult<SearchInvoiceInfoResponseBO> searchInvoiceInfo(@RequestBody SearchInvoiceInfoRequestBO request) {
        return JSONResult.success(organizationInfoService.searchInvoiceInfo(request));
    }

    /**
     * 批量转移人员到其他组织
     *
     * @return
     */
    @PostMapping(value = "/batchTransferEmployeeOrgInfo")
    public JSONResult batchTransferEmployeeOrgInfo(@RequestBody TransferEmployeeOrgInfoVo request) {
        return new JSONResult(organizationInfoService.batchTransferEmployeeOrgInfo(request));
    }

    /**
     * 根据orgId获取 组织架构链路到子公司  -->样式：GROUP>机票事业部>测试
     *
     * @param orgId
     * @return
     */
    @PostMapping("/getFullLinkByOrgId")
    public JSONResult<String> getFullLinkByOrgId(@RequestParam(value = "orgId") String orgId) {
        List<OrgInfoVo> orgInfoList = organizationInfoService.getOrgInfoList(orgId, true);
        if (CollectionUtils.isNotEmpty(orgInfoList)) {
            orgInfoList.sort(Comparator.comparing(OrgInfoVo::getLevel));
            return JSONResult.success(orgInfoList.stream().map(OrgInfoVo::getName).collect(Collectors.joining(">")));
        }
        return JSONResult.ok();
    }

    /**
     * 查询所有子部门信息
     * @param orgId
     * @return
     */
    @RequestMapping("/findAllDepartmentIds")
    public JSONResult<List<String>> findAllDepartmentIds(@RequestParam(value = "orgId") String orgId) {
        GetOrgTreeRequest request = new GetOrgTreeRequest();
        request.setOrgId(orgId);
        request.setIsErgodic(true);
        return new JSONResult(organizationInfoService.listAllDepartmentByOrgId(request));
    }

    @PostMapping("/wholeOrgTree")
    @ResponseBody
    public JSONResult<List<OrgAndDataPermissionInfoBO>> wholeOrgTree(@RequestBody GetOrgTreeReq request) {
        return JSONResult.success(organizationInfoService.wholeOrgTree(request));
    }

    @RequestMapping("/modifyPassenger")
    public JSONResult<Boolean> modifyPassenger(@RequestBody PassengerModifyRequest passengerModifyRequest, BaseUserInfo baseUserInfo){
        log.info("开始修改乘机人信息");
        return organizationInfoService.modifyPassenger(passengerModifyRequest, baseUserInfo);
    }

    @RequestMapping("/nameRepeatQuery")
    public JSONResult<Boolean> nameRepeatQuery(@RequestBody NameRepeatQueryRequest nameRepeatQueryRequest){
        return JSONResult.success(organizationInfoService.nameRepeatQuery(nameRepeatQueryRequest));
    }

    /**
     * 查询当前登录用户能看到的所有组织
     *
     * @param request
     * @return
     */
    @ApiOperation("查询登录用户数据权限下所有的组织信息")
//    @PostMapping("/queryOrgIdWithPermission")
    @PostMapping(value = "/queryOrgIdWithPermission", consumes = "application/json")
    public JSONResult<QueryOrgInfoWithPermissionResponse> queryOrgIdWithPermission(
            @RequestBody QueryOrgInfoWithPermissionRequest request) {
        return JSONResult.success(organizationInfoService.queryOrgIdWithPermission(request));
    }

    /**
     * 根据businessCode查询对应组织信息
     * @param businessCode
     * @return
     */
    @RequestMapping(value = "/findAllByBusinessCodeList")
    public JSONResult<List<OrgInfoVo>> findAllByBusinessCodeList(@RequestBody List<String> businessCode) {
        if (CollectionUtils.isNotEmpty(businessCode)) {
            return JSONResult.success(organizationInfoService.findAllByBusinessCodeList(businessCode));
        }
        return JSONResult.errorMsg("orgIds is empty");
    }

    @RequestMapping("/listOrgTreeByCondition")
    @ResponseBody
    public JSONResult<List<ListOrgTreeByConditionResponse>> listOrgTreeByCondition(@RequestBody ListOrgTreeByConditionRequest request, BaseUserInfo baseUserInfo) {
        return JSONResult.success(organizationInfoService.listOrgTreeByCondition(request, baseUserInfo));
    }
}
